import pandas as pd
import sqlalchemy

# 从CSV文件中提取数据，并将其作为pandas DataFrame返回
def extract_data(csv_name):
    df_pd = pd.read_csv(csv_name)
    return df_pd

# 将DataFrame保存到数据库表
def saveToPg(df_pd, tbname):
    # 设置openGauss数据库版本信息
    from sqlalchemy.dialects.postgresql.base import PGDialect
    PGDialect._get_server_version_info = lambda *args: (9, 2)
    # 构造连接字符串
    userName = 'myroot'
    password = 'myroot_123'
    dbHost = '10.10.74.207'
    dbPort = 15400
    dbName = 'app'
    DB_CONNECT = f'postgresql://{userName}:{password}@{dbHost}:{dbPort}/{dbName}'
    # 创建SQLAlchemy连接
    conn = sqlalchemy.create_engine(DB_CONNECT)
    if conn:
        print("连接openGauss成功")
    # 将DataFrame写入数据库
    df_pd.to_sql(tbname, conn, if_exists='replace', index=False)
    print("存储成功")

if __name__ == "__main__":
    table_name = "installinfos"
    # 从CSV文件中提取数据到DataFrame
    df = extract_data(table_name + ".csv")
    # 打印CSV数据中的行数
    print(f"csv数据条数：{len(df)}")
    # 将DataFrame保存到OpenGauss表中
    saveToPg(df, table_name)